<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>
			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">

							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">

									<u-col span="4">
										<u-form-item labelWidth="auto" label="报废单号:">
											<u--input v-model="baseFormData.BillNO" readonly border="none"
												placeholder="自动带出报废单号"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报废模具:" @click="openBaseScreen('模具')"
											required>
											<u--input v-model="baseFormData.MoludName" placeholder="请选择报废模具" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报废人员:">
											<u--input v-model="baseFormData.BFMan" readonly border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>

								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报废类型:" required
											@click="openBaseScreen('报废类型')">
											<u--input v-model="baseFormData.ScrapType" readonly placeholder="请选择报废类型"
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报废时间:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动带出报废时间" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="报废原因:" required>
											<u--input v-model="baseFormData.BFCause" placeholder="请输入报废原因"
												border="none"></u--input>
										</u-form-item>
									</u-col>


								</u-row>
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="审核状态:">
											<u--input v-model="baseFormData.ApproveStatus" placeholder="自动带出审核状态"
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="8">
										<u-form-item labelWidth="auto" label="备注:">
											<u--input v-model="baseFormData.FRemarks" placeholder="请输入备注"
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
							</u--form>
						</view>

					</view>
					<view class=" DetailsbottomBtns">
						<button block @click="submit" class="button1">
							保存
						</button>
						<button class="button2" :class="baseFormData.Approve ? 'approved' : 'pending'" block
							@click="ToExamine" v-show="ToExamineShow">
							{{ToExamineName}}
						</button>
					</view>

				</view>
			</template>
		</st-mc-framework>

		<u-toast ref="uToast"></u-toast>
		<u-datetime-picker :show="Timeshow" v-model="value1" mode="date" @cancel='Timeshow=false'
			@confirm='pickerConfirm'></u-datetime-picker>

		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';

	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {
				baseFormData: {
					BillNO: '',
					ScrapType: '',
					BFCause: '',
					ScrapMould: 0,
					BFMan: '',
					BillDate: '',
					MoludName: '',
					MoludID: '',
					FRemarks: '',
					ApproveStatus: ''
				},
				Timeshow: false,
				value1: Number(new Date()),
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
				ToExamineShow: false,
				ToExamineName: '审核',
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;

			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName;
			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (onLoad.ScrapMould) {
				setLoading(true);
				this.queryList(onLoad.ScrapMould);
				return;
			}
			if (onLoad.Detailsitem) {
				setLoading(true);
				const dispatchItem = JSON.parse(onLoad.Detailsitem);
				const formDefaults = {
					...dispatchItem,
					MoludName: dispatchItem.MoludCode
				}
				console.log(formDefaults);
				this.baseFormData = Object.assign(this.baseFormData, formDefaults);
			}
			// 统一处理表单默认值
			const formDefaults = {
				BFMan: UserInfo.EmplName,
				CheckupID: UserInfo.EmplID,
				BillDate: getFormatDateTime(new Date())
			};
			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);

		},

		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onShow() {
			var that = this
			uni.$on('refreshDetail', (res) => {
				console.log(res.data);
				this.getValue(res.data); // 调用目标方法
			});
		},
		onUnload() {
			uni.$off('refreshDetail');
		},
		methods: {

			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},

			getValue(payload) {
				var that = this;
				const {
					type,
					...data
				} = payload;
				if (payload === '返回') return;
				const typeHandlers = {
					'模具': () => ({
						MoludID: data.MoludID,
						MoludName: data.MoludCode
					}),
					'报废类型': () => ({
						ScrapType: data.NAME,
					}),

				};
				if (typeHandlers[type]) {
					Object.assign(this.baseFormData, typeHandlers[type]());
				}
			},
			openBaseScreen(str) {
				var that = this;
				var obj;
				if (str == '模具') {
					obj = {
						cmd: 'ZS_Droplist_Molud',
						type: str,
						serverSearch: {
							isPaging: true, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'MoludCode', //查询结果显示的字段
						},
						param: {
							MoludID: 0,
							FWorkshopID: that.FWorkshopID,
							MoludCode: '',
							PageIndex: 1,
							PageSize: 30
						}
					}
				} else if (str == '报废类型') {
					obj = {
						cmd: 'getMoldBFType',
						type: str,
						serverSearch: {
							isPaging: false, //是否分页
							pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中		
							searchShow: false, //是否查询
							searchKey: 'searchKey', //搜索关键词，应包含在param中
							showText: 'NAME', //查询结果显示的字段
						},
						param: {
							PageIndex: 1,
							PageSize: 30
						}
					}
				}
				uni.navigateTo({
					url: `../common/baseScreen?obj=${JSON.stringify(obj)}`,
					animationType: 'slide-in-right',
					animationDuration: 300
				});
			},

			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				const formDefaults = {
					BillDate: time
				};
				this.assignFormData(this.baseFormData, formDefaults);
				this.Timeshow = false
			},
			// 审核/取消审核
			ToExamine() {
				if (this.ToExamineName == '取消审核') {
					this.SJJ_ApproveChange(this.ToExamineName, this.baseFormData.ScrapMould)
				} else {
					this.submit(this.ToExamineName)
				}
			},
			// 审核
			SJJ_ApproveChange(str, ScrapMould) {
				let that = this;
				var msg
				var Approve
				switch (str) {
					case '审核':
						Approve = 1
						msg = '审核成功'
						break;
					case '取消审核':
						Approve = 0
						msg = '撤审成功'
						break;

				}
				var obj1 = {
					ScrapMould: ScrapMould,
					ApproveStatus: Approve,
					MoludID: that.baseFormData.MoludID,
				}
				console.log(obj1);

				that.Request.request('approveScrapMould', obj1, function(res) {
					that.$refs.uToast.show({
						title: '保存',
						type: 'success',
						message: msg
					})
					that.queryList(ScrapMould);
				}, function(err) {
					console.log(err)
				})
			},
			submit(str) {
				var that = this
				var msg
				var show = true
				console.log(this.baseFormData);
				if (that.baseFormData.MoludName == '' || that.baseFormData.MoludName == null) {
					msg = '请输入模具'
					show = false
				} else if (that.baseFormData.ScrapType == '' || that.baseFormData.ScrapType == null) {
					msg = '请选择报废类型'
					show = false
				} else if (that.baseFormData.BFCause == '' || that.baseFormData.BFCause == null) {
					msg = '请输入报废原因'
					show = false
				}

				if (show) {
					var obj = {
						BFMan: that.baseFormData.BFMan,
						MoludID: that.baseFormData.MoludID,
						ScrapMould: that.baseFormData.ScrapMould ? that.baseFormData
							.ScrapMould : 0,
						BillDate: that.baseFormData.BillDate,
						ScrapType: that.baseFormData.ScrapType,
						BFCause: that.baseFormData.BFCause,
						FRemarks: that.baseFormData.FRemarks,
					}
					console.log(obj);
					that.Request.request('saveScrapMould', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							var ScrapMould = ret.data.ds[0].ScrapMould
							switch (str) {
								case '保存':
									that.$refs.uToast.show({
										title: '保存',
										type: 'success',
										message: '保存成功'
									})
									setTimeout(() => {
										that.queryList(ScrapMould)
									}, 1000)
									break;
								case '审核':
									that.SJJ_ApproveChange(str, ScrapMould)
									break;

									// default:
									// break;
							}

						}
					})
				} else {
					that.showModal('报错', msg);
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getScrapMouldDetail', {
						ScrapMould: id
					}, (ret) => {
						that.showMLoading = false
						console.log(ret.data);
						const [firstItem] = ret.data.ds;
						if (firstItem.ScrapMould) {
							that.ToExamineShow = true
							that.ToExamineName = firstItem.Approve == true ? '取消审核' : '审核'
							firstItem.ApproveStatus = firstItem.Approve == true ? '已审核' : '未审核'
						}
						const formDefaults = {
							...firstItem,
							BillDate: firstItem.BillDate ? firstItem.BillDate.split('T')[0] : ''
						};

						that.assignFormData(that.baseFormData, formDefaults)


					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";

	.approved {
		background-color: #FFD700 !important;

	}


	.pending {
		background-color: #dbb56a !important;
	}
</style>